/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "uart_control.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

#define RX_BUF_SIZE 64  // 接收缓存数组大小
uint8_t rx_buf[RX_BUF_SIZE];  // 存储接收到的原始数据
volatile uint8_t rx_flag = 0;  // 接收完成标志位（volatile防止编译器优化）
uint8_t FLAG_500ms = 0;  // 500ms标志位
uint8_t FLAG_1000ms = 0;  // 1s标志位
uint8_t FLAG_2000ms = 0;  // 2s标志位
uint8_t FLAG_5000ms = 0;  // 5s标志位
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/**
 * 脉冲控制
*/
void Motor_X_CW(void);
void Motor_X_CCW(void);
void Motor_Y_CW(void);
void Motor_Y_CCW(void);
void Moto_X_Rotate(double rs);
void Moto_Y_Rotate(double rs);

/**
 * 输出重定向
 */ 
int fputc(int ch, FILE *f)
{
  uint8_t temp[1] = {ch};
  HAL_UART_Transmit(&huart1, temp, 1, 2);
  return ch;
}

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/**
 * TIMER
*/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_TIM1_Init();
  MX_TIM3_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_TIM2_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
  HAL_TIM_Base_Start_IT(&htim2);
  // HAL_UART_Receive_DMA(&huart2, rx_buf, RX_BUF_SIZE);
  HAL_UARTEx_ReceiveToIdle_DMA(&huart2, rx_buf, RX_BUF_SIZE);
  // __HAL_DMA_DISABLE_IT(&hdma_usart2_rx, DMA_IT_HT);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  // motor_enable(0x01, 0x00, 0x00);

  while (1)
  {
    if (FLAG_500ms) {
      FLAG_500ms = 0;  // 清除标志位
    }
    if (FLAG_1000ms) {
      FLAG_1000ms = 0;  // 清除标志位
    }
    if (FLAG_2000ms) {
      FLAG_2000ms = 0;  // 清除标志位
      
      
      // generate_motor_commands(x, 1000, 100);
    }
    if (FLAG_5000ms) {
      FLAG_5000ms = 0;  // 清除标志位
    }

    // 使能电机
    // motor_enable(0x01, 0x01, 0x00);
    // HAL_Delay(2000);
    // motor_enable(0x01, 0x00, 0x00);

    // 电机画圆(未添加插补算法)
    // motor_circle(100);
    // uint16_t speed_rpm = 100;
    // for (int i = 0; i < 2000; i = i+50)
    // {
    //   // generate_motor_commands(i, i, 1500);
    //   set_position(1, i, 0, speed_rpm, 0);
    //   HAL_Delay(10);
    //   set_position(2, i, 0, speed_rpm, 0);
      // HAL_Delay(10);
    // }

    // 

    // generate_motor_commands(-2000, 1000, 100);  // X轴运动，速度50RPM
     
    // HAL_Delay(2000);
    
    // uint8_t cmd1[13] = {0x01, 0xFD, 0x00, 0x07, 0xD0, 0x 00, 0x00, 0x00, 0x0C, 0x80, 0x00, 0x00, 0x6B};
    // HAL_UART_Transmit_DMA(&huart2, cmd1, sizeof(cmd1));

    // 发送位置控制命令
    // set_position(1, 3200, 0, 500, 0);
    // printf("Sent position command.\r\n");

    // 查询电机位置
    // get_position(1);  // 获取电机1的当前位置
    // HAL_Delay(5);

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

void Motor_X_CW(void)
{
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
}

void Motor_X_CCW(void)
{
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
}

void Motor_Y_CW(void)
{
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
}

void Motor_Y_CCW(void)
{
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
}

void Moto_X_Rotate(double rs)
{
  float f = 3200 * rs;

  int cnt = (int)(1000000.0/f);
  __HAL_TIM_SetAutoreload(&htim1, cnt);
  __HAL_TIM_SetCompare(&htim1, TIM_CHANNEL_1, cnt/2);
}

void Moto_Y_Rotate(double rs)
{
  float f = 3200 * rs;

  int cnt = (int)(1000000.0/f);
  __HAL_TIM_SetAutoreload(&htim3, cnt);
  __HAL_TIM_SetCompare(&htim3, TIM_CHANNEL_1, cnt/2);
}

/**
 * @brief 定时器回调函数
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if(htim == &htim2)
  {
    /* 1ms timer */
     static uint16_t cnt = 0;
    
    if (htim == &htim2) {
        cnt++;
        if (cnt >= 500) {  // 500ms = 0.5秒
            FLAG_500ms = 1;  // 设置500ms标志位
        }
        if (cnt >= 1000) {  // 1秒
            FLAG_1000ms = 1;  // 设置1s标志位    
        }
        if (cnt >= 2000) {  // 2秒
            
            FLAG_2000ms = 1;  // 设置2s标志位
        }
        if (cnt >= 5000) {  // 5秒
            cnt = 0;  // 重置计数器
            
            FLAG_5000ms = 1;  // 设置5s标志位
        }        
    }
  }
}

// /**
//  * @brief UART接收完成回调函数
//  */
// void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
//   printf("Received data: ");
//   if (huart == &huart2) {
//     if (rx_buf[0] == 0x01 && rx_buf[1] == 0xFD && rx_buf[2] == 0x02 && rx_buf[3] == 0x6B) {
//       printf("Position move started!\r\n");
//     }
//     if (rx_buf[0] == 0x01 && rx_buf[1] == 0xF3 && rx_buf[2] == 0x02 && rx_buf[3] == 0x6B) {
//       printf("Changed state!\r\n");
//     }
//     else {
//       printf("Error code received!\r\n");
//       printf("%02X %02X %02X %02X\r\n", rx_buf[0], rx_buf[1], rx_buf[2], rx_buf[3]);
//     }
//     HAL_UART_Receive_DMA(&huart2, rx_buf, RX_BUF_SIZE); // 重新启动接收
//   }
// }

// /**
//  * @brief UART不定长接收回调函数
//  */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) {
  printf("Received data: ");
  if (huart == &huart2) {
    // 打印接收到的数据
    // HAL_UART_Transmit_DMA(&huart1, rx_buf, Size);
    
    if (rx_buf[0] == 0x01 && rx_buf[1] == 0xFD && rx_buf[2] == 0x02 && rx_buf[3] == 0x6B) { 
      printf("Position move started!\r\n");
    }
    if (rx_buf[0] == 0x01 && rx_buf[1] == 0xF3 && rx_buf[2] == 0x02 && rx_buf[3] == 0x6B) {
      printf("Changed status!\r\n");
    }
    if (rx_buf[0] == 0x01 && rx_buf[1] == 0x36) { // 位置查询响应
      uint8_t direction = (rx_buf[2] == 0x00) ? '+' : '-';
      printf("Current position: %c%d\r\n", direction, 
             ((rx_buf[3] << 24) | (rx_buf[4] << 16) | (rx_buf[5] << 8) | rx_buf[6]));
    }
    if (rx_buf[0] == 0x01 && rx_buf[1] == 0x00 && rx_buf[2] == 0xEE && rx_buf[3] == 0x6B){
      printf("Error code!!!\r\n");
    }
    HAL_UARTEx_ReceiveToIdle_DMA(&huart2, rx_buf, RX_BUF_SIZE); // 重新启动DMA接收
  }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
